//
//  SearchDeviceViewController.m
//  LightControl
//
//  Created by CKF on 2025/8/11.
//

#import "SearchDeviceViewController.h"
#import "SharedManager.h"
#import "DeviceItemCollectionViewCell.h"
#import "DeviceViewController.h"
#import "DeviceFanLightViewController.h"
@interface SearchDeviceViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>
@property (nonatomic, strong) UIButton *searchBtn;
@property (nonatomic, strong) UIButton *bottomBtn;
@property (nonatomic, strong) UIButton *bleBtn;
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) UIView *lineView;
@property (nonatomic, strong) UIView *line;
@property (nonatomic, assign) BOOL isOn; //蓝牙状态是否正常
@property (nonatomic, assign) BOOL isSearching;//正在搜索
@end

@implementation SearchDeviceViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"Scan";
    [self initCollectionView];
    [self addRigthItems];
    [self addBottomBtn];
    [self addLineView];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(checkBluetoothState:) name:@"checkBluetoothState" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deviceAccept) name:@"deviceAccept" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(finishScan) name:@"finishScan" object:nil];
    [[SharedManager sharedInstance] setBabyDelegate];
}

-(void)initCollectionView{
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, KScreenWidth , KScreenHeight-mNavBarHeight) collectionViewLayout:layout];
    [self.view addSubview:self.collectionView];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.backgroundColor = [UIColor whiteColor];
    [self.collectionView registerClass:[DeviceItemCollectionViewCell class] forCellWithReuseIdentifier:NSStringFromClass([DeviceItemCollectionViewCell class])];
}

#pragma mark - UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
//    return 5;
    return [SharedManager sharedInstance].deviceArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    //重用cell
    DeviceItemCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([DeviceItemCollectionViewCell class]) forIndexPath:indexPath];
    UIImage *image = [UIImage imageNamed:@"Lightble"];
    UIImage *templateImage = [image imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];

    // 3. 创建 UIImageView 并设置 tintColor
    cell.imgView.image = templateImage;
    cell.imgView.tintColor = RGB(60, 157, 239); // 替换为红色
    cell.titleLabel.text = @"11122332441";
    cell.detailLabel.text = @"威磁0xCD01";
    return cell;
}

-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(20, 20, 20, 20);
}

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(KScreenWidth*0.5-30, 130);
}

#pragma mark - 设置每个UICollectionView最小垂直间距

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 20;
}

#pragma mark - 设置每个UICollectionView最小水平间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 20;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {
        DeviceViewController *vc = [[DeviceViewController alloc]init];
        [self.navigationController pushViewController:vc animated:YES];
    }else{
        
        DeviceFanLightViewController *vc = [[DeviceFanLightViewController alloc]init];
        [self.navigationController pushViewController:vc animated:YES];
    }
}

-(void)addLineView{
    _lineView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, KScreenWidth, 4)];
    _lineView.backgroundColor = RGB(207, 225, 244);
    [self.view addSubview:_lineView];
    
    _line = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 100, 4)];
    _line.backgroundColor = RGB(42, 87, 126);
    [_lineView addSubview:_line];
    _lineView.hidden = YES;
}

-(void)finishScan{
    _isSearching = NO;
    _lineView.hidden = YES;
    [_bottomBtn setImage:[UIImage imageNamed:@"Search"] forState:0];
    [_bottomBtn setBackgroundColor:RGB(118, 163, 213)];
    [_searchBtn setTitle:LocalString(@"搜索") forState:0];
}


//蓝牙状态
-(void)checkBluetoothState:(NSNotification *)noti{
    NSString *state = noti.userInfo[@"state"];
    if ([state intValue] == 1) {
        [_bleBtn setImage:[UIImage imageNamed:@"ble_on"] forState:0];
    }else{
        [_bleBtn setImage:[UIImage imageNamed:@"ble_off"] forState:0];
        if (_isSearching) {
            [[SharedManager sharedInstance] stopScan];
        }
    }
}

//F2接收的设备数据
-(void)deviceAccept{
    [_bottomBtn setBackgroundColor:RGB(118, 163, 213)];
    [_bottomBtn setImage:[UIImage imageNamed:@"Search"] forState:0];
    [_searchBtn setTitle:LocalString(@"搜索") forState:0];
}

-(void)addBottomBtn{
    _bottomBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _bottomBtn.frame = CGRectMake(KScreenWidth-80, self.view.frame.size.height-80-mNavBarHeight, 60, 60);
    [_bottomBtn setBackgroundColor:RGB(118, 163, 213)];
    _bottomBtn.layer.cornerRadius = 15;
    [_bottomBtn setImage:[UIImage imageNamed:@"Search"] forState:0];
    [_bottomBtn addTarget:self action:@selector(searchBtnAct) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_bottomBtn];
}

-(void)addRigthItems{
    _bleBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 35, 34)];
    [_bleBtn setImage:[UIImage imageNamed:@"ble_off"] forState:0];
    [_bleBtn addTarget:self action:@selector(bleBtnAct) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *bleItem = [[UIBarButtonItem alloc] initWithCustomView:_bleBtn];
    
    UIButton *guideBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 34, 34)];
    [guideBtn setImage:[UIImage imageNamed:@"Help"] forState:0];
    [guideBtn addTarget:self action:@selector(guideBtnAct) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *guideItem = [[UIBarButtonItem alloc] initWithCustomView:guideBtn];
    
    _searchBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _searchBtn.frame = CGRectMake(0, 0, 60, 30);
    [_searchBtn setBackgroundColor:[UIColor whiteColor]];
    [_searchBtn setTitle:LocalString(@"搜索") forState:0];
    _searchBtn.layer.cornerRadius = 15;
    _searchBtn.titleLabel.font = [UIFont systemFontOfSize:13];
    [_searchBtn setTitleColor:RGB(48, 89, 126) forState:0];
    [_searchBtn addTarget:self action:@selector(searchBtnAct) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *searchItem = [[UIBarButtonItem alloc] initWithCustomView:_searchBtn];
    self.navigationItem.rightBarButtonItems = @[searchItem,guideItem,bleItem];
}



-(void)bleBtnAct{
    
}

-(void)guideBtnAct{
    
}

-(void)searchBtnAct{
    
    _isSearching = !_isSearching;
    if (_isSearching) {
        [_bottomBtn setImage:[UIImage imageNamed:@"stop"] forState:0];
        [_searchBtn setTitle:LocalString(@"停止") forState:0];
        [_bottomBtn setBackgroundColor:RGB(255, 55, 55)];
//        [[SharedManager sharedInstance] startScan];
        _line.frame = CGRectMake(0, 0, 100, 4);
        _lineView.hidden = NO;
        
        // 创建宽度动画
        CABasicAnimation *widthAnim = [CABasicAnimation animationWithKeyPath:@"bounds.size.width"];
        widthAnim.fromValue = @(80);
        widthAnim.toValue = @(250); // 第一阶段宽度变化
        widthAnim.beginTime = 0.0; // 立即开始
        widthAnim.duration = 0.6;

        // 创建X位移动画（第一阶段）
        CABasicAnimation *positionAnim1 = [CABasicAnimation animationWithKeyPath:@"position.x"];
        positionAnim1.fromValue = @(40); // 初始中心点X
        positionAnim1.toValue = @(KScreenWidth-60-125); // 新中心点X = x起点 + 宽度/2 (120+100=220)
        positionAnim1.beginTime = 0.0;
        positionAnim1.duration = 0.6;

        // 第二阶段动画（宽度20 → X起点300）
        CABasicAnimation *widthAnim2 = [CABasicAnimation animationWithKeyPath:@"bounds.size.width"];
        widthAnim2.fromValue = @(250);
        widthAnim2.toValue = @(40);
        widthAnim2.beginTime = 0.6; // 第1秒开始
        widthAnim2.duration = 0.4;

        CABasicAnimation *positionAnim2 = [CABasicAnimation animationWithKeyPath:@"position.x"];
        positionAnim2.fromValue = @(KScreenWidth-60-125); // 上一阶段终点
        positionAnim2.toValue = @(KScreenWidth-20); // 新中心点X = 300 + 宽度/2 (300+10=310)
        positionAnim2.beginTime = 0.6;
        positionAnim2.duration = 0.4;

        // 组合动画
        CAAnimationGroup *group = [CAAnimationGroup animation];
        group.animations = @[widthAnim, positionAnim1, widthAnim2, positionAnim2];
        group.duration = 1;
        group.fillMode = kCAFillModeForwards; // 保持最终状态
        group.removedOnCompletion = NO; // 防止动画移除后还原
        group.repeatCount = 10;
        group.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
        // 应用动画并更新模型层
        [_line.layer addAnimation:group forKey:@"groupAnimation"];
        [[SharedManager sharedInstance] advertisementF1Data];
    }else{
        [[SharedManager sharedInstance] stopScan];
    }
    
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
